package com.rpay.admin.controller.task;

import com.rpay.common.dto.user.UserDTO;
import com.rpay.common.dto.user.UserTradeDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.exception.UserException;
import com.rpay.common.util.DateUtil;
import com.rpay.dao.user.UserTradeDao;
import com.rpay.model.trade.TradeCacheDO;
import com.rpay.model.user.UserTradeDO;
import com.rpay.service.trade.ITradeCacheService;
import com.rpay.service.user.IUserService;
import com.rpay.service.user.IUserTradeService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

@Component
public class UserTradeTask {

    static public Timer timer;

    @Autowired
    private UserTradeDao userTradeDao;

    @Autowired
    private IUserService userService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IUserTradeService iUserTradeService;

    @Autowired
    private ITradeCacheService tradeCacheService;

    // 充值账单地址
    @Value("${ripple.paymentUrl}")
    private String paymentUrl;

    // 每分钟取一次账单
    @Scheduled(fixedDelay = 60 * 1000)
    public void userTrade() { // todo start参数
        Calendar currentDate = new GregorianCalendar();
        currentDate.add(Calendar.DATE, -1);    //得到前一天
        String startDate = DateUtil.formatDate(currentDate.getTime());
        System.out.println(paymentUrl + "&start=" + startDate);
        ResponseEntity<String> response = restTemplate
                .getForEntity(paymentUrl + "&start=" + startDate, String.class);
        String body = response.getBody();

        if (response.getStatusCode() == HttpStatus.OK) {
            JSONObject rst = new JSONObject(body);
            if (rst.get("result").equals("success")) {
                List<UserTradeDO> userTrades = iUserTradeService.getTradesByExecTime();
                JSONArray array = rst.getJSONArray("payments");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject payment = array.getJSONObject(i);
                    System.out.println(isExit(payment, userTrades));
                    if (!isExit(payment, userTrades)) {
                        try {
                            UserTradeDTO userTradeDTO = new UserTradeDTO();
                            String amountStr = payment.getString("amount");
                            BigDecimal amount = new BigDecimal(amountStr);
                            String executedTime = payment.getString("executed_time");
                            Integer tag = payment.getInt("destination_tag");
                            String source = payment.getString("source");
                            userTradeDTO.setType("INVEST");
                            userTradeDTO.setStatus("END");
                                userTradeDTO.setInvest_wallet(source);
                            userTradeDTO.setTx_hash(payment.getString("tx_hash"));
                            userTradeDTO.setRippleAmount(amount);
                            userTradeDTO.setRpayAmount(amount);
                            userTradeDTO.setUserId(tag);

                            UserDTO userDTO = userService.getUserById(tag);
                            System.out.println(tag);
                            System.out.println(amount);
                            System.out.println(userDTO);
                            if (userDTO != null) {
                                iUserTradeService.saveUserTrade(userTradeDTO);
                                // 确认充值需要添加用户的瑞波币余额
                                BigDecimal userRippleAmount = userDTO.getRippleAmount();
                                userDTO.setRippleAmount(userRippleAmount.add(amount));
                                userService.updateUser(userDTO);
                            }
                        } catch (Exception e) {
                            System.out.println(e);
                        }

                    }
                }
            }
        }
    }

    private Boolean isExit(JSONObject payment, List<UserTradeDO> userTrades) {
        Boolean exit = false;
        for (UserTradeDO userTradeDO : userTrades) {
            String hash = userTradeDO.getTx_hash();
            if (hash != null && hash.equals(payment.get("tx_hash"))) {
                exit = true;
            }
        }
        return exit;
    }
}
